package com.zxl.controller;

import com.zxl.constants.RedisConstants;
import com.zxl.feign.GoodsFeign;
import com.zxl.vo.Car;
import com.zxl.vo.Customer;
import com.zxl.vo.Goods;
import com.zxl.vo.R;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;


/**
 * @packageName com.zxl.controller
 * @ClassName
 * @Author zxl
 * @Description //TODO
 * @date
 **/
@Controller
@RequestMapping("/car")
public class CarController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private GoodsFeign goodsFeign;

    @RequestMapping("/add")
    @ResponseBody
    public R add(HttpSession session, Car car,
                 @CookieValue(name = RedisConstants.CAR_COOKIE, defaultValue = "") String anonId,
                 HttpServletResponse response) {

        Customer customer = (Customer) session.getAttribute(RedisConstants.USER_LOGIN_SESSION_KEY);
        BoundHashOperations<String, Object, Object> carMap = null;
        if (customer != null) {
            carMap = redisTemplate.boundHashOps(RedisConstants.CAR_MAP_KEY + customer.getId());

        } else {
            if (StringUtils.isEmpty(anonId)) {
                anonId = UUID.randomUUID().toString().replace("-", "");
                Cookie cookie = new Cookie(RedisConstants.CAR_COOKIE, anonId);
                cookie.setMaxAge(60 * 60 * 24 * 7); // 7天
                cookie.setPath("/"); // 跨域问题
                response.addCookie(cookie);
            }
            carMap = redisTemplate.boundHashOps(RedisConstants.CAR_MAP_KEY + anonId);

        }
        Integer sum = car.getSum();
        if (carMap.hasKey(car.getGid().toString())) {
            sum += Integer.parseInt(carMap.get(car.getGid()).toString());
        }
        carMap.put(car.getGid().toString(), sum.toString());
        return R.success();
    }


    /**
     * @param anonId
     * @param cId
     * @param response 用户登陆时合并购物车
     */
    @RequestMapping("/merge")
    @ResponseBody
    public void merge(@RequestParam("anonId") String anonId, @RequestParam("cId") String cId, HttpServletResponse response) {

        System.out.println(anonId + "---" + cId);

        BoundHashOperations<String, Object, Object> aonon = redisTemplate.boundHashOps(RedisConstants.CAR_MAP_KEY + anonId);
        BoundHashOperations<String, Object, Object> c = redisTemplate.boundHashOps(RedisConstants.CAR_MAP_KEY + cId);
        Map<Object, Object> map = aonon.entries();
        for (Object o : map.keySet()) {
            String s = o.toString();
            Integer sum = Integer.parseInt(map.get(s).toString());
            if (c.hasKey(s)) {
                sum += Integer.parseInt(c.get(s).toString());
            }
            c.put(s, sum.toString());
        }
        redisTemplate.delete(RedisConstants.CAR_MAP_KEY + anonId);
        Cookie cookie = new Cookie(RedisConstants.CAR_COOKIE, "");
        response.addCookie(cookie);

    }

    @RequestMapping("/list")
    public String list(HttpSession session,
                       @CookieValue(name = RedisConstants.CAR_COOKIE, defaultValue = "") String anonId,
                       Model model) {
        BoundHashOperations<String, Object, Object> aonon = null;
        Customer customer = (Customer) session.getAttribute(RedisConstants.USER_LOGIN_SESSION_KEY);
        BoundHashOperations<String, Object, Object> c = null;
        List<Car> carList = new ArrayList<>();
        Double totalPrice = 0.0;
        if (!StringUtils.isEmpty(anonId)) {
            aonon = redisTemplate.boundHashOps(RedisConstants.CAR_MAP_KEY + anonId);
            Map<Object, Object> map = aonon.entries();
            addCarToList(carList, map);
        }
        if (customer != null) {
            c = redisTemplate.boundHashOps(RedisConstants.CAR_MAP_KEY + customer.getId());
            Map<Object, Object> map = c.entries();
            addCarToList(carList, map);

        }
        for (Car car : carList) {
            totalPrice += car.getSumPrice();
        }
        model.addAttribute("totalPrice", totalPrice);
        model.addAttribute("carList", carList);
        return "carList";
    }


    @RequestMapping("/listByUidAndGid")
    @ResponseBody
    public Map<String, Object> carListByGidAndUid(@RequestParam("uid") Integer uid, @RequestParam("gids") String[] gids) {
        BoundHashOperations<String, Object, Object> u =
                redisTemplate.boundHashOps(RedisConstants.CAR_MAP_KEY + uid);
        List<Car> carList = new ArrayList<>();
        Map<Object, Object> map = u.entries();
        Double totalPrice = 0.0;
        if (gids != null && gids.length > 0) {
            for (String gid : gids) {
                if (map.containsKey(gid)) {
                    String sum = (String) map.get(gid);
                    Car car = new Car();
                    carList(carList, gid, sum, car);
                }
            }
        }else {
            addCarToList(carList,map);
        }

        for (Car car : carList) {
            totalPrice += car.getSumPrice();
        }

        Map<String, Object> result = new HashMap<>();
        result.put("carList", carList);
        result.put("totalPrice", totalPrice);
        return result;
    }

    private void carList(List<Car> carList, String gid, String sum, Car car) {
        Goods goods = goodsFeign.findById(Integer.parseInt(gid));
        car.setGid(Integer.parseInt(gid));
        car.setSum(Integer.parseInt(sum));
        car.setSumPrice(Integer.parseInt(sum) * goods.getGprice());
        car.setGoods(goods);
        carList.add(car);
    }


    private void addCarToList(List<Car> carList, Map<Object, Object> map) {

        for (Object o : map.keySet()) {
            Car car = new Car();
            String s = o.toString();
            String sum = map.get(s).toString();
            carList(carList, s, sum, car);
        }
    }


    @RequestMapping("/update")
    @ResponseBody
    public R update(Integer gid, String type,
                    @CookieValue(name = RedisConstants.CAR_COOKIE) String anonId,
                    HttpSession session) {

        Customer customer = (Customer) session.getAttribute(RedisConstants.USER_LOGIN_SESSION_KEY);
        BoundHashOperations<String, Object, Object> map = null;
        if (!StringUtils.isEmpty(anonId)) {
            map = redisTemplate.boundHashOps(RedisConstants.CAR_MAP_KEY + anonId);
        }
        if (customer != null) {
            map = redisTemplate.boundHashOps(RedisConstants.CAR_MAP_KEY + customer.getId());
        }

        switch (type) {
            case "incr":
                map.increment(gid + "", 1);
                break;
            case "decr":
                map.increment(gid + "", -1);
                break;
        }

        return R.success();
    }


}
